
import 'dart:convert';
import 'dart:core' as prefix0;
import 'dart:core';

import 'package:dio/dio.dart';
import 'package:flustars/flustars.dart';
import 'baseentity.dart';
import 'errorhandle.dart';
import 'intercept.dart';

/**
 * lx
 * git：https://gitee.com/twopai
 * dio封装，可设置header、baseUrl、拦截器
 */
class DioUtils {

  static final DioUtils _singleton = DioUtils._internal();

  static DioUtils get instance => DioUtils();

  static  String _baseUrl='https://www.chinawylm.com/api.php/';

  factory DioUtils() {
    return _singleton;
  }

  static Dio _dio;

  DioUtils._internal(){
    var options = BaseOptions(
      connectTimeout: 15000,
      receiveTimeout: 30000,
      responseType: ResponseType.plain,
      validateStatus: (status){
        // 不使用http状态码判断状态，使用AdapterInterceptor来处理（适用于标准REST风格）
        return true;
      },
      baseUrl: _baseUrl,
    );
    _dio = Dio(options);
    /// 打印Log
    _dio.interceptors.add(LoggingInterceptor());
    /// 适配数据
    _dio.interceptors.add(AdapterInterceptor());
  }
  //初始化dio
  initDio({String baseUrl:''}){
    _baseUrl=baseUrl;
  }

  //添加拦截器
  DioUtils addInterceptor({Interceptor interceptor}){
    if(interceptor!=null)_dio?.interceptors?.add(interceptor);
    return this;
  }
  //切换baseUrl
  DioUtils setBaseUrl({String baseUrl:''}){
    if((baseUrl??'').isEmpty){
      _dio?.options?.baseUrl=_baseUrl;
    }else{
      _dio?.options?.baseUrl=baseUrl;
    }
    return this;
  }
  //设置 Headers
  DioUtils setHeaders({List<Map<String,dynamic>> headers}){
    if((headers??[]).isNotEmpty){
      headers?.forEach((element) {
        _dio?.options?.headers?.addAll(element);
      });
    }
    return this;
  }

  Options _checkOptions(method, Options options) {
    if (options == null) options = new Options();
    if(options.headers==null){
      options.headers={};
    }
    // options.headers.addAll({'Authorization':'Bearer ${Provider.of<UserProvider>(navigatorKey.currentContext,listen: false)?.access_token}'});
    // options.headers.addAll({'Authorization':'Bearer ${SpUtils.getString(Constants.access_token)}'});
    options.method = method;
    return options;
  }

  // 数据返回格式统一，统一处理异常
  Future<BaseEntity> _request(String method, String url, {
    dynamic data,Map<String, dynamic> queryParameters, CancelToken cancelToken, Options options}) async {
    var response = await _dio.request(url, data: data, queryParameters:queryParameters,options: _checkOptions(method, options), cancelToken: cancelToken);
    LogUtil.e('_request-->response=$response');
    int _code;
    String _msg;
    bool _more;
    dynamic _total;
    dynamic _data;

    try {
      Map<String, dynamic> _map = json.decode(response.data.toString());
      _code = _map["code"];
      _msg = _map["msg"];
      _more = _map["more"];
      _total = _map["total"];
      _data = _map["data"];
    }catch(e){
      print(e);
      return parseError();
    }
    return BaseEntity(
        _code, _msg, _data,
        total: _total,more: _more
    );
  }

  /// 统一处理
  requestNetwork(String method, String url, {dynamic params,Map<String, dynamic> queryParameters, CancelToken cancelToken, Options options})async{
    if(queryParameters==null)queryParameters={};
   print("listen： params: ${params?.toString()}");
    try{
      var result= await _request(method, url, data: params,queryParameters: queryParameters, options: options, cancelToken: cancelToken);
      return BaseEntity(
        result.code, result.msg,result.data,total: result?.total,more: result?.more,
      );
    }catch(e){
      LogUtil.e("请求的接口 0-->e=${e?.toString()}");
      Error error = ExceptionHandle.handleException(e);
      return BaseEntity(error.status, error.message,null);
    }
  }
  BaseEntity parseError(){
    return BaseEntity(ExceptionHandle.parse_error, "数据解析错误", null);
  }
  /***********************************************/
  /*
   * 下载文件
   */
  downloadFile(urlPath, savePath,{Function(int count, int total) onProgress,Function() onSuccess,Function(Exception e) onFail,Map<String, dynamic> params,}) async {
    Response response;
    var options = BaseOptions(
      connectTimeout: 15000,
      receiveTimeout: 15000,
      responseType: ResponseType.plain,
      validateStatus: (status){
        // 不使用http状态码判断状态，使用AdapterInterceptor来处理（适用于标准REST风格）
        return true;
      },
//      baseUrl: Constant.BASE_URL,
//      contentType: ContentType('application', 'x-www-form-urlencoded', charset: 'utf-8'),
    );
    Dio _dio2 = Dio(options);
    /// 统一添加身份验证请求头
//    _dio2.interceptors.add(AuthInterceptor());
//    /// 刷新Token
//    _dio2.interceptors.add(TokenInterceptor());
//    /// 打印Log
//    _dio2.interceptors.add(LoggingInterceptor());
//    /// 适配数据
//    _dio2.interceptors.add(AdapterInterceptor());
    try {
      response = await _dio2.download(urlPath, savePath,data: params,onReceiveProgress: (int count, int total){
        //进度
        print("下载文件进度-->$count $total");
        onProgress(count,total);
      });
      onSuccess();
      print('downloadFile success---------${response.data}');
    } on DioError catch (e) {
      print('downloadFile error---------$e');
//      formatError(e);
      onFail(e);
    }
//    return response.data;
  }
  // 上传文件
  static Future<Response> uploadFile(String path ,{FormData data}) async{
    var options = BaseOptions(
      connectTimeout: 15000,
      receiveTimeout: 15000,
      responseType: ResponseType.plain,
      validateStatus: (status){
        // 不使用http状态码判断状态，使用AdapterInterceptor来处理（适用于标准REST风格）
        return true;
      },
//      baseUrl: Constant.BASE_URL,
//      contentType: ContentType('application', 'x-www-form-urlencoded', charset: 'utf-8'),
    );
    Dio _dioUp = Dio(options);
    Response response = await _dioUp.post(path,data: data);
    print('uploadFile-->response=${response?.toString()}');
    return response;
  }

}